<?php
session_start();
?>
<?php include 'config.php';

// 检查文章ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: index.php');
    exit;
}

$articleId = $_GET['id'];

// 获取文章
$stmt = $pdo->prepare("SELECT * FROM aiwz_articles WHERE id = :id");
$stmt->bindParam(':id', $articleId);
$stmt->execute();
$article = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$article) {
    header('Location: index.php');
    exit;
}

// 获取底部配置
$stmt = $pdo->query("SELECT * FROM aiwz_settings LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

// 解析Markdown内容                  
$parsedown = new Parsedown();
$htmlContent = $parsedown->text($article['markdown_content']);
//$htmlContent = Markdown::defaultTransform($article['markdown_content']);
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($article['title']); ?> - Markdown博客</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css">
    <style>
        /* 表格整体样式 */
        table {
            border-collapse: collapse;
            /* 合并边框 */
            width: 100%;
            /* 可选：表格宽度 */
            margin: 10px 0;
            /* 可选：上下外边距 */
        }

        /* 表头和单元格样式 */
        th,
        td {
            border: 1px solid #ddd;
            /* 边框颜色（浅灰色） */
            padding: 10px;
            /* 内边距 */
            text-align: left;
            /* 文字左对齐 */
        }

        /* 可选：表头背景色 */
        th {
            background-color: #f5f5f5;
        }

        .article-content img {
            max-width: 100%;
            height: auto;
            margin: 1rem 0;
        }

        .article-content pre {
            background-color: #f8f9fa;
            padding: 1rem;
            border-radius: 5px;
            overflow-x: auto;
        }

        .article-content blockquote {
            border-left: 4px solid #ddd;
            padding-left: 1rem;
            margin-left: 0;
            color: #666;
        }

        .footer-section {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        .qrcode-container {
            text-align: center;
            margin: 20px 0;
        }

        .qrcode-container img {
            max-width: 200px;
            height: auto;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
        <div class="container">
            <a class="navbar-brand" href="index.php">Markdown博客</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="create.php">发布文章</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="settings.php">设置</a>
                    </li>
                </ul>
                <!-- 根据登录状态显示不同内容 -->
                <?php if (isset($_SESSION['user_id'])): ?>
                    <div class="dropdown">
                        <button class="btn btn-outline-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <?php echo htmlspecialchars($_SESSION['username']); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="logout.php">退出登录</a></li>
                        </ul>
                    </div>
                <?php else: ?>
                    <!-- 未登录：显示登录按钮 -->
                    <a href="login.php" class="btn btn-outline-light">登录</a>
                <?php endif; ?>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <article>
                    <h1 class="mb-4"><?php echo htmlspecialchars($article['title']); ?></h1>

                    <div class="mb-4 text-muted">
                        <span class="badge bg-secondary"><?php echo htmlspecialchars($article['category']); ?></span>
                        <span class="ms-2">发布于:
                            <?php echo date('Y-m-d H:i', strtotime($article['created_at'])); ?></span>
                        <?php if ($article['created_at'] != $article['updated_at']): ?>
                            <span class="ms-2">更新于:
                                <?php echo date('Y-m-d H:i', strtotime($article['updated_at'])); ?></span>
                        <?php endif; ?>
                    </div>

                    <div class="mb-4">
                        <?php
                        $tags = explode(',', $article['tags']);
                        foreach ($tags as $tag) {
                            echo '<span class="badge bg-primary me-1">' . htmlspecialchars(trim($tag)) . '</span>';
                        }
                        ?>
                    </div>

                    <div class="article-content mb-5">
                        <?php echo $htmlContent; ?>
                    </div>

                    <!-- 统一添加的底部内容 -->
                    <div class="footer-section">
                        <p><?php echo nl2br(htmlspecialchars($settings['footer_text'])); ?></p>
                        <div class="qrcode-container">
                            <?php if (!empty($settings['qrcode_image']) && file_exists('uploads/' . $settings['qrcode_image'])): ?>
                                <img src="uploads/<?php echo htmlspecialchars($settings['qrcode_image']); ?>" alt="赞助二维码">
                            <?php else: ?>
                                <img src="https://via.placeholder.com/200" alt="赞助二维码">
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="mt-4">
                        <a href="edit.php?id=<?php echo $article['id']; ?>" class="btn btn-outline-primary">编辑文章</a>
                        <button class="btn btn-outline-danger ms-2"
                            onclick="if(confirm('确定要删除这篇文章吗？')) window.location.href='delete.php?id=<?php echo $article['id']; ?>'">删除文章</button>
                        <a href="index.php" class="btn btn-outline-secondary ms-2">返回列表</a>
                    </div>
                </article>
            </div>
        </div>
    </div>

    <footer class="bg-dark text-white mt-5 py-4">
        <div class="container text-center">
            <p>&copy; <?php echo date('Y'); ?> Markdown博客 - 用技术记录生活</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <script>hljs.highlightAll();</script>

    <script>
        // 等待页面加载完成
        document.addEventListener('DOMContentLoaded', function () {
            // 获取当前网站的域名（不含协议和端口）
            const currentDomain = window.location.hostname;

            // 获取页面中所有链接
            const links = document.querySelectorAll('a');

            // 遍历所有链接
            links.forEach(link => {
                // 获取链接的href属性
                const href = link.getAttribute('href');

                // 跳过没有href或href为空的链接
                if (!href) return;

                // 处理相对路径（如 "/home" 或 "page.html"）
                // 相对路径默认视为本站链接
                if (href.startsWith('/') || !href.startsWith('http')) {
                    link.target = '_self'; // 当前窗口打开（默认值，可省略）
                    return;
                }

                // 解析绝对路径的域名
                try {
                    const url = new URL(href);
                    const linkDomain = url.hostname;

                    // 比较链接域名与当前网站域名
                    if (linkDomain === currentDomain) {
                        // 本站链接：当前窗口打开
                        link.target = '_self';
                    } else {
                        // 外站链接：新窗口打开
                        link.target = '_blank';
                        // 推荐添加rel属性增强安全性
                        link.rel = 'noopener noreferrer';
                    }
                } catch (e) {
                    // 解析URL失败时（如无效链接），默认当前窗口打开
                    link.target = '_self';
                }
            });
        });
    </script>
</body>

</html>